import React from "react";
import style from "./index.module.scss";
import hearder from "../../base/Header";
import {request} from "../../request/request";
import store from "../../Store";

import {Image, Avatar,Divider} from "antd";
import {Button,InputItem } from "antd-mobile";
const bookCoverDefault = require("../../common/imageDefault/book-cover-default.png").default;


import { v4 as uuidv4 } from 'uuid';

// 消息样本
let message = {
	// 查询字段
	mid: "uuid",
	isdel:"0",
	buildtime:new Date(),
	// 发送者信息
	fromUid:"",
	fnickname:"",
	fhead_url:"",
	fstuAuth:"",
	// 接收者信息
	toUid:"",
	tnickname:"",
	thead_url:"",
	tstuAuth:"",
	// 信息内容
	type: "chat",
	message:"信息内容",
	sendtime:new Date(),
	readtime:new Date(),
	// 携带商品
	bid:"",
	cover:"",
	name:"",
	despcription:"",
	price:"",
	origin_price:"",
}

const buildMessage = (reactHost)=>{
    let {userInfo,currentMsg} = reactHost.state;
    let toUserInfo = reactHost.props.location.state;

    let msgObj = {
        // 查询字段
        mid: uuidv4(),
        isdel: 0,
        // 发送者信息
        fromUid: userInfo.uid,
        fnickname: userInfo.nickname,
        fhead_url: userInfo.head_url,
        fstuAuth: userInfo.stuAuth,
        // 接收者信息
        toUid: toUserInfo.toUid,
        tnickname: toUserInfo.tnickname,
        thead_url: toUserInfo.thead_url,
        tstuAuth: toUserInfo.tstuAuth,
        // 信息内容
        type: "chat",
        message: currentMsg,
        sendtime: new Date().getTime(),
        readtime: "",
        // 携带商品
        bid: toUserInfo.bid,
        cover: toUserInfo.cover,
        name: toUserInfo.name,
        despcription: toUserInfo.despcription,
        price: toUserInfo.price,
        origin_price: toUserInfo.origin_price,
    }

    for(let key in msgObj){
        if((!msgObj[key] && msgObj[key] != 0)||msgObj[key]==null){
            msgObj[key] = 0;
        }
    }

    return msgObj;
}

// 需要的信息
// fromUserInfo: 当前登录用户
// toUserInfo: 通过 toUid(uid) 查询
// 携带商品信息 bid cover ... 传过来
// 通过 fromUid + toUid 从数据中获取消息列表 (仓库)

// 用户对话框
    // 〇、监控仓库消息队列 （监听）
    // 一、跳转来源：
    //     1、消息中心
    //         从仓库中获取对应的消息列表
    //     2、图书详情
    //         从数据库中获取相关的消息列表 ？ 
    //     3、客服中心
    //         通过我的页面获取相关客服交流信息
    //         从数据库中获取相关的消息列表
    // 二、发送消息
    //     将当前消息对象填充到仓库 当前发送消息


class PrivateChat extends React.Component {
    constructor(props){
        super(props);
        this.props = props;

        this.state={
            userInfo:{
                uid:"",
                nickname:"我的昵称",
                head_url:"",
                stuAuth:1,
            },
            toUserInfo:{
                uid:"",
                nickname:"对方昵称",
                head_url:"",
                stuAuth:1,
            },
            bookinfo:{
                bid:"",
            },
            currentMsg:"",
            msgList:[]
        }
    }

    // 获取图书详情
    getBookInfo(bid){
        request({
            url:"/bookinfo",
            method:"GET",
            params:{
                uid:"",
                bid,
            }
        }).then(res=>{
            console.log(res);
            if(res.data.code==="01"){
                if(typeof res.data.data !== "object"){
                   alert("请求数据失败")
                }else{
                    let bookinfo = {...res.data.data};
                    let toUserInfo = {
                         uid: bookinfo.uid,
                         nickname: bookinfo.nickname,
                         head_url: bookinfo.head_url,
                         stuAuth: bookinfo.stuAuth,
                    }
                    this.setState({bookinfo, toUserInfo});
                    setTimeout(()=>{
                        console.log("-->",this.state);
                    },100);
                }
            }
        })
    }
    // 获取卖家详情
    getSellerInfo(){
        
    }

    sendMessageStore(){
        let messageObj = buildMessage(this);
        store.dispatch({type:"PULLCMESSAGE",data:messageObj});
        this.setState({currentMsg:""});
    };

    componentDidMount(){
        let temp = localStorage.getItem("userList");
        if(temp) this.setState({userInfo:JSON.parse(temp)});

        let {bid,toUid} = this.props.location.state;
        if(bid) this.getBookInfo(bid);
        else if(toUid) console.log("toUid-->",toUid)
        let {toUserInfo} = this.props.location.state
        console.log("toUserInfo",toUserInfo)

        let {messageList} = store.getState();
        this.setState({msgList:messageList});
        setTimeout(()=>{
            this.msglistWarp.scrollTo({
                top:this.msglistWarpInner.offsetHeight - this.msglistWarp.clientHeight,
            });
        },300)

        setTimeout(()=>{
            this.unsubscribe = store.subscribe(()=>{
                let {messageList} = store.getState();
                this.setState({msgList:messageList});
                this.msglistWarp.scrollTo({
                    top:this.msglistWarpInner.offsetHeight - this.msglistWarp.clientHeight,
                    behavior:"smooth",
                });
            });
        },300)
    }
    componentWillUnmount(){
        this.unsubscribe();
        store.dispatch({type:"PULL_lastPathname",data:"/privateChat"});
    }

    render(){
        let toUserInfo = this.props.location.state;

        let {userInfo, bookinfo, msgList} = this.state;

        let messages = msgList.filter(msg => msg.type="chat" && (msg.message || msg.message == 0));
        let timeInter = [];
        let msgItem = messages.map((msg,ii)=>{
            timeInter.push(new Date(Number(messages[ii].sendtime)));
            let msgTypeClassName = "";
            if(msg.fromUid === userInfo.uid && msg.toUid === toUserInfo.toUid){
                msgTypeClassName = "msg-fromme";
            }
            // else if(msg.fromUid === toUserInfo.uid  && msg.toUid === userInfo.uid) msgTypeClassName = "msg-tome";
            else msgTypeClassName = "msg-tome";

            return (
                <div key={ii} className={style["msg-item"]}>
                    {msgTypeClassName == "msg-tome"
                        ?<div className={style[msgTypeClassName]}>
                            <p>{msg.message}</p>
                            <Avatar
                                style={{
                                    color: '#fff',
                                    backgroundColor:"rgb(0, 89, 255)"
                                }}
                                >{toUserInfo.tnickname.substr(0,1)}</Avatar>
                        </div>
                        :<div className={style[msgTypeClassName]}>
                            <Avatar
                                style={{
                                    color: '#fff',
                                    fontWeight:"700",
                                    backgroundColor: 'rgb(250, 108, 51)',
                                }}
                                >我</Avatar>
                            <p>{msg.message}</p>
                        </div>
                    }
                    
                </div>
            )
        });

        let count = 0;
        timeInter.forEach((timespan,ii)=>{
            if(ii && timespan - timeInter[ii-1] > 60*1000*5){
                let target = <Divider key={timespan.getTime()} className={style["msg-divider"]}>{timespan.toLocaleString()}</Divider>
                ++count;
                msgItem.splice(ii+count-1,0,target)
            }
        })

        // msgItem.unshift(<Divider key={timeInter[0].getTime()} className={style["msg-divider"]}>{timeInter[0].toLocaleString()}</Divider>)

        return (
            <div className={style["index-root"]}>
                {hearder({ history:this.props.history,
                    title:toUserInfo.tnickname+`${toUserInfo.tstuAuth?"(学生认证)":""}`
                })}

                { bookinfo.bid && 
                    <div className={style["bookinfo-box"]}>
                        <Image className={style["bookcover"]} src={bookinfo.cover} fallback={bookCoverDefault} />
                        <div className={style["infobox"]}>
                            <h3>{bookinfo.name}</h3>
                            <p>{bookinfo.description}</p>
                        </div>
                        <div className={style["op-box"]}>
                            <Button className={style["btn"]}
                                onClick={()=>{ this.props.history.push(`/bookInfoDetails/${bookinfo.bid}`)}}
                            >立即购买</Button>
                        </div>
                    </div>
                }

                <div className={style["msg-container"]} style={!bookinfo.bid ? {height:"calc(100% - 115px)"}:null}
                    ref={msglistWarp => this.msglistWarp=msglistWarp}
                >
                    <div className={style["msglist-warp"]} ref={msglistWarpInner => this.msglistWarpInner=msglistWarpInner}>
                        {msgItem}
                    </div>
                </div>

                <div className={style["sendop-box"]}>
                    <InputItem className={style["inputitem"]} value={this.state.currentMsg} placeholder="想和TA说点什么···" 
                        onChange = {(value)=>{this.setState({currentMsg:value})}}
                    />
                    <Button className={style["sendbtn"]}
                        onClick={this.sendMessageStore.bind(this)}
                    >发送</Button>
                </div>
            </div>
        )
    }
}

export default PrivateChat;

// const mapStateToProps = (state)=>{
//     return {
//         messageList: state.messageList
//     };
// }
// const mapDispatchToProps= (dispatch)=>{
//     return {
//         addMessage:(message)=>{
//             dispatch({type:"ADDMESSAGE",data:message})
//         },
//         clearMessage:()=>{
//             dispatch({type:"CLEARMESSAGE"});
//         },
//         pullCMessage:(message)=>{
//             dispatch({type: "PULLCMESSAGE",data: message})
//         },
//         clearCMessage:(message)=>{
//             dispatch({type: "CLEARCMESSAGE", data: message})
//         },
//     }
// }
// export default connect(mapStateToProps,mapDispatchToProps)(PrivateChat);